﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TankShooting1 : MonoBehaviour
{
    public int m_PlayerNum = 1;
    public Slider m_ShootSlider;
    public Rigidbody m_Shell;
    public AudioSource m_ShootAudio;
    public AudioClip m_ShootClip;
    public AudioClip m_ChargeClip;
    public Transform m_ShootTransform;
    public float m_MaxLaunchForce = 30f;
    public float m_MinLaunchForce = 15f;
    public float m_ChargeTime = 0.75f;

    private string m_ShootBtnName;
    private float m_CurrentLaunchForce;
    private float m_ChargeSpeed;
    private bool m_Fired;

    private void OnEnable()
    {
        m_CurrentLaunchForce = m_MinLaunchForce;
        m_ShootSlider.value = m_MinLaunchForce;
    }

    private void Start()
    {
        m_ShootBtnName = "Fire" + m_PlayerNum;
        m_ChargeSpeed = (m_MinLaunchForce / m_MaxLaunchForce) / m_ChargeTime;
    }

    private void Update()
    {
        m_ShootSlider.value = m_MinLaunchForce;
        if(m_CurrentLaunchForce > m_MaxLaunchForce && !m_Fired)
        {
            m_CurrentLaunchForce = m_MaxLaunchForce;
            Fire();
        }
        else if (Input.GetButtonDown(m_ShootBtnName))
        {
            m_Fired = false;
            m_CurrentLaunchForce = m_MinLaunchForce;

            m_ShootAudio.clip = m_ChargeClip;
            m_ShootAudio.Play();
        }
        else if(Input.GetButton(m_ShootBtnName) && !m_Fired){
            m_CurrentLaunchForce += m_ChargeSpeed;
            m_ShootSlider.value = m_CurrentLaunchForce;
        }
        else if(Input.GetButtonUp(m_ShootBtnName) && !m_Fired)
        {
            Fire();
        }
    }

    void Fire()
    {
        m_Fired = true;
        Rigidbody shellInstance = Instantiate(m_Shell, m_ShootTransform) as Rigidbody;
        
        shellInstance.position = m_ShootTransform.position;
        shellInstance.velocity = m_ShootTransform.forward * m_CurrentLaunchForce;
        m_ShootAudio.clip = m_ShootClip;
        m_ShootAudio.Play();
        m_CurrentLaunchForce = m_MinLaunchForce;
    }

}
